package com.example.finalassessment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.finalassessment.dao.ProductMapper;
import com.example.finalassessment.dto.CategoryProductCountDTO;
import com.example.finalassessment.model.Category;
import com.example.finalassessment.dao.CategoryMapper;
import com.example.finalassessment.model.Product;
import com.example.finalassessment.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author funny_chao
 * @since 2024-12-09
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private ProductMapper productMapper;

    // 获取每个分类的商品数量
    public List<CategoryProductCountDTO> getCategoryProductCount() {
        // 获取所有分类
        List<Category> categories = this.list();

        // 获取每个分类下商品的数量
        return categories.stream()
                .map(category -> {
                    // 查询该分类下商品的数量
                    Long count = productMapper.selectCount(
                            new QueryWrapper<Product>().eq("category_id", category.getId())
                    );
                    return new CategoryProductCountDTO(category.getName(), count);
                })
                .collect(Collectors.toList());
    }


}
